/*
COPYRIGHT (C) 2009 EPISERVER AB

THIS FILE IS PART OF VIRTUAL ROLES SAMPLE PACK FOR EPISERVER CMS.
DYNAMIC CONTENT CONTRIB FOR EPISERVER CMS IS FREE SOFTWARE: YOU CAN REDISTRIBUTE IT AND/OR MODIFY IT UNDER THE TERMS OF THE GNU LESSER GENERAL PUBLIC LICENSE VERSION v2.1 AS PUBLISHED BY THE FREE SOFTWARE FOUNDATION.

VIRTUAL ROLES SAMPLE PACK FOR EPISERVER CMS IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU LESSER GENERAL PUBLIC LICENSE FOR MORE DETAILS.
YOU SHOULD HAVE RECEIVED A COPY OF THE GNU LESSER GENERAL PUBLIC LICENSE ALONG WITH VIRTUAL ROLES SAMPLE PACK FOR EPISERVER CMS. IF NOT, SEE <HTTP://WWW.GNU.ORG/LICENSES/>.
*/
using System;
using System.Collections.Generic;
using System.Text;
using EPiServer;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.Web.PropertyControls;
using EPiServer.Web.WebControls;
using System.Web.Security;
using System.Web.UI.WebControls;
using System.Linq;
using EPiServer.Security;


namespace EPiServer.Research.RoleBasedContent
{
    /// <summary>
    /// PropertyControl implementation used for rendering RoleSelector data.
    /// </summary>
    public class RoleSelectorControl : EPiServer.Web.PropertyControls.PropertyStringControl
    {

        protected ListBox list;

        public override void CreateEditControls()
        {
            list = new ListBox();
            list.SelectionMode = ListSelectionMode.Multiple;
            list.DataSource = EPiServer.Security.RoleProviderUtility.GetAllRolesWithProviders().Select(ri => ri.RoleName).Union(EPiServer.Security.VirtualRoles.GetAllRoles());
            
            list.DataBind();
            Controls.Add(list);
            SetupEditControls();
        }

        protected override void SetupEditControls()
        {
            var r = RoleSelector.Roles;
            foreach (ListItem li in list.Items)
            {
                if (r.Contains(li.Text)) li.Selected = true;
            }
        }

        public override void ApplyEditChanges()
        {
            List<string> rt=new List<string>();
            foreach (ListItem li in list.Items)
            {
                if (li.Selected) rt.Add(li.Text);
            }
            RoleSelector.Roles = rt.ToArray();
        }
        

        /// <summary>
        /// Gets the RoleSelector instance for this IPropertyControl.
        /// </summary>
        /// <value>The property that is to be displayed or edited.</value>
        public RoleSelector RoleSelector
        {
            get
            {
                return PropertyData as RoleSelector;
            }
        }
    }
}
